﻿using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace SPSource.Lists
{
    public class ListTemplateDependentFilesGenerator
    {
        /// <summary>
        /// A ListTemplate schema.xml file requires it's view files and form files.
        /// This method creates these files by reaching out to the List using the object model.
        /// </summary>
        /// <param name="featureRootDirectoryPath"></param>
        /// <param name="listName"></param>
        /// <param name="webUrl"></param>
        public static void GenerateDependentFiles(DirectoryInfo directory, string listName, string webUrl, bool overrideFeatureDirectoryCheck)
        {
            //TODO: refactor as in schema generator too
            string listStaticName = SPStringUtility.RemoveNonAlphaNumericChars(listName);
            DirectoryInfo listSchemaDirectory = directory.CreateSubdirectory(listStaticName);
            
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(webUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists[listName];
                        foreach (SPForm form in list.Forms)
                        {
                            FileInfo file = WriteFileFromSharePointList(web, form.Url, listSchemaDirectory.FullName);
                            //only add if in feature folder
                            if (!overrideFeatureDirectoryCheck) 
                                FeatureManager.AddElementFileToFeature(file);
                        }

                        foreach (SPView view in list.Views)
                        {
                            FileInfo file = WriteFileFromSharePointList(web, view.Url, listSchemaDirectory.FullName);
                            //only add if in feature folder
                            if (!overrideFeatureDirectoryCheck) 
                                FeatureManager.AddElementFileToFeature(file);
                        }
                        if (list is SPDocumentLibrary)
                        {
                            string documentTemplateUrl = ((SPDocumentLibrary)list).DocumentTemplateUrl;
                            if (!string.IsNullOrEmpty(documentTemplateUrl))
                            {
                                FileInfo file = WriteFileFromSharePointList(web, documentTemplateUrl, listSchemaDirectory.FullName);
                                //only add if in feature folder
                                if (!overrideFeatureDirectoryCheck) 
                                    FeatureManager.AddElementFileToFeature(file);
                            }
                        }
                    }
                }
            });
        }

        public static FileInfo WriteFileFromSharePointList(SPWeb web, string fileUrl, string filePath)
        {
            SPFile spFile = web.GetFile(fileUrl);

            byte[] fileBytes = spFile.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);

            string newFilePath = filePath + "\\" + spFile.Name;
            if (File.Exists(newFilePath))
                File.Delete(newFilePath);

            FileStream fsFile = File.Create(newFilePath);
            fsFile.Write(fileBytes, 0, fileBytes.Length);
            fsFile.Close();
            return new FileInfo(newFilePath);
        }
    }
}
